﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CLEXA.DataContracts;

namespace CLEXA.DAL
{
    public class HistogramDAL : IHistogramDAL
    {
        public List<HistogramRowData> ExecuteQuery(string connectionString, string sql)
        {
            List<HistogramRowData> result = new List<HistogramRowData>();

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.CommandType = CommandType.Text;

                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        List<int> strings = new List<int>();
                        List<int> doubles = new List<int>();

                        for (int i = 0; i < reader.VisibleFieldCount; i++)
                        {
                            Console.WriteLine(reader.GetFieldType(i));
                            if (reader.GetFieldType(i) == typeof(string))
                            {
                                strings.Add(i);
                            }
                            else if (reader.GetFieldType(i) == typeof(float))
                            {
                                doubles.Add(i);
                            }
                        }
                        double[] values = new double[doubles.Count];

                        do
                        {
                            StringBuilder group = new StringBuilder();
                            for (int i = 0; i < strings.Count; i++)
                            {
                                if (i != 0)
                                {
                                    group.AppendLine();
                                }
                                group.Append(reader.GetString(strings[i]));
                            }

                            for (int i = 0; i < doubles.Count; i++)
                            {
                                values[i] = reader.GetFloat(doubles[i]);
                            }

                            result.Add(new HistogramRowData(group.ToString(), values));

                        } while (reader.Read());
                    }
                }
            }

            return result;
        }
    }
}
